<!doctype html>
<html lang="en">

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Todo List</title>
	<link rel="stylesheet" href="assets/css/base.css">
	<link rel="stylesheet" href="assets/css/index.css">
</head>

<body>
	<section class="todoapp">
		<header class="header">
			<h1>todos</h1>
			<input class="new-todo" placeholder="What needs to be done?" autofocus>
		</header>
		<!-- This section should be hidden by default and shown when there are todos -->
		<section class="main">
			<input class="toggle-all" type="checkbox">
			<label for="toggle-all">Mark all as complete</label>
			<ul class="todo-list" id="todo-list">
				<!-- These are here just to show the structure of the list items -->
				<!-- List items should get the class `editing` when editing and `completed` when marked as completed -->

			</ul>
		</section>
		<!-- This footer should hidden by default and shown when there are todos -->
		<footer class="footer">
			<!-- This should be `0 items left` by default -->
			<span class="todo-count"><strong>0</strong> item left</span>
			<!-- Remove this if you don't implement routing -->
			<ul class="filters">
				<li>
					<a class="footerBtn selected" id="showAllTask" href="javascript:;">All</a>
				</li>
				<li>
					<a class="footerBtn" id="showActivcTask" href="javascript:;">Active</a>
				</li>
				<li>
					<a class="footerBtn" id="showCompletedTask" href="javascript:;">Completed</a>
				</li>
			</ul>
			<!-- Hidden if no completed items are left ↓ -->
			<button class="clear-completed">Clear completed</button>
		</footer>
	</section>
</body>

<script src="/js/jquery.min.js"></script>
<script src="/js/template-web.js"></script>
<script type="text/html" id="taskTpl">
		{{ each taskArr v }}
		<li data-id="{{ v._id }}" class="itemTask {{ v.completed ? 'completed' : '' }}">
			<div class="view">
				<input class="toggle" type="checkbox" {{ v.completed ? 'checked' : '' }}>
				<label>{{ v.title }}</label>
				<button class="destroy"></button>
			</div>
			<input class="edit" value="Create a TodoMVC template">
		</li>
		{{ /each }}
</script>

<script>
	$(() => {
		// 存放任务清单的ul
		const $todoListContainer = $('#todo-list')
		// 任务未完成数
		const $todoCount = $('.todo-count>strong')
		// 总任务列表
		let taskArr = []
		// 当前任务列表
		let curTaskArr = []

		const renderTaskList = () => {
			$todoListContainer.html(template('taskTpl', { taskArr: curTaskArr }))
			$todoCount.html(taskArr.filter(v => !v.completed).length)
		}

		$.ajax({
			type: 'GET',
			url: '/todo/task',
			success(res) {
				// console.log(res);
				taskArr = curTaskArr = res
				renderTaskList()
			}
		})

		// 获取到输入任务信息的输入框
		const $newTodoInp = $('.new-todo')
		// 绑定键盘弹起事件 新增任务功能
		$newTodoInp.keyup(({ keyCode }) => {
			// 当摁下回车键
			if (keyCode === 13) {
				const title = $newTodoInp.val().trim()
				$newTodoInp.val('')
				if (title === '') return
				// 判断输入的任务是否已存在
				if (taskArr.some(v => v.title === title)) return alert('该任务已存在！')

				$.ajax({
					type: 'POST',
					url: '/todo/addTask',
					contentType: 'application/json',
					data: JSON.stringify({ title }),
					success(res) {
						taskArr.push(res)
						renderTaskList()
					}
				})
			}

		})

		// 删除功能
		$todoListContainer.on('click', '.destroy', ({ target }) => {
			$.ajax({
				type: 'GET',
				url: '/todo/deleteTask',
				data: { _id: $(target).parents('.itemTask').data('id') },
				success({ _id }) {
					// 服务端返回被删除的任务对象 如果有_id证明删除成功
					if (_id) {
						taskArr = curTaskArr = taskArr.filter(v => v._id != _id)
						renderTaskList()
					}
				}
			})

		})

		// 任务状态切换功能
		$todoListContainer.on('change', '.toggle', ({ target }) => {
			// 拿到切换后的状态
			const { checked } = target
			const id = $(target).parents('.itemTask').data('id')

			$.ajax({
				type: 'POST',
				url: '/todo/updateTask',
				contentType: 'application/json',
				// 需要将数据转换为json字符串
				data: JSON.stringify({
					_id: id,
					completed: checked
				}),
				success(res) {
					taskArr.find(v => v._id === res._id).completed = res.completed
					renderTaskList()
				}
			})

		})

		// 双击修改任务功能
		$todoListContainer.on('dblclick', 'label', ({ target }) => {
			$(target).parents('.itemTask').addClass('editing')
			$(target).parent().siblings('.edit').val(target.innerHTML).focus()

		})
		$todoListContainer.on('blur', '.edit', ({ target }) => {
			const id = $(target).parents('.itemTask').data('id')
			const val = target.value.trim()
			val.value = ''
			const oldTask = taskArr.find(v => v._id === id)
			// 验证是否改动
			if (val === oldTask.title) {
				$(target).parents('.itemTask').removeClass('editing')
				return
			}
			// 验证是否任务重名
			if (taskArr.some(v => v.title === val)) return alert('该任务已存在')

			$.ajax({
				type: 'POST',
				url: '/todo/updateTask',
				contentType: 'application/json',
				data: JSON.stringify({
					_id: id,
					title: target.value.trim()
				}),
				success(res) {
					oldTask.title = target.value.trim()
					renderTaskList()
				}
			})

		})

		$('#showAllTask').on('click', ({ target }) => {
			curTaskArr = taskArr
			$('.footerBtn').removeClass('selected')
			$(target).addClass('selected')
			renderTaskList()
		})
		$('#showActivcTask').on('click', ({ target }) => {
			curTaskArr = taskArr.filter(v => !v.completed)
			$('.footerBtn').removeClass('selected')
			$(target).addClass('selected')
			renderTaskList()
		})
		$('#showCompletedTask').on('click', ({ target }) => {
			curTaskArr = taskArr.filter(v => v.completed)
			$('.footerBtn').removeClass('selected')
			$(target).addClass('selected')
			renderTaskList()
		})

	})
</script>

</html>